package view;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.SystemColor;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.Arrays;

import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.ScrollPaneConstants;
import javax.swing.SwingConstants;
import javax.swing.UIManager;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import model.Account;
import model.Encryption;
import model.FormatFactory;
import model.NumberRenderer;
import model.StoreImages;
import model.SystemTableModel;
import model.UICommand;

import org.jdesktop.swingx.JXCollapsiblePane;
import org.jdesktop.swingx.JXSearchField;
import org.jdesktop.swingx.JXSearchField.LayoutStyle;
import org.jdesktop.swingx.JXTable;
import org.jdesktop.swingx.JXTextField;

import test.TestString;

import com.alee.laf.WebLookAndFeel;
import com.alee.laf.toolbar.WebToolBar;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.RowSpec;

import controller.SystemController;

public class SystemPanel extends JPanel {
	private static final long serialVersionUID = -9046197820279907511L;
	private JXTable table;
	private JPopupMenu popupMenu;
	private JXCollapsiblePane advanced;
	private JTextField textField_3;
	private static final String[] USER = { "User", "Admin" };
	private SystemController control;
	private JXTextField a_username;
	private JXTextField a_author;
	private JPasswordField a_password;
	private JPasswordField a_reenter;
	private JComboBox<String> a_combobox;
	private JMenuItem mnDel;
	private JMenuItem mnNotify;
	private JLabel a_label1;
	private JLabel a_label2;
	private JLabel a_label3;
	private JLabel a_label4;
	private JLabel a_label5;
	private JButton btnAdd;
	private static final String DEFAULT_USERNAME = "Tên tài khoản tối thiểu 5 kí tự, tối đa 45 kí tự";
	private static final String DEFAULT_AUTHOR = "Tối thiểu 1 kí tự tối đa 45 kí tự";
	private static final String DEFAULT_PASS = "Ít nhất 6 kí tự hoặc số";
	private SystemTableModel tableModel;
	private JCheckBox chck_name;
	private JTextField txt_name;
	private JCheckBox check_author;
	private JTextField txt_author;
	private JCheckBox check_lastloggin;
	private JTextField txt_lastloggin;
	private JCheckBox check_lock;
	private JCheckBox check_exe;
	private JComboBox<String> cbx_lock;
	private JComboBox<String> cbx_exe;
	private JXSearchField searchField;
	private ArrayList<JCheckBox> listChckBox;
	private WebToolBar toolBar;
	private JMenuItem mntmThmTiKhon;
	private JPanel account;
	private boolean modify;

	public SystemPanel(SystemTableModel tableModel,
			final SystemController control) {
		this.tableModel = tableModel;
		this.control = control;
		this.listChckBox = new ArrayList<>();
		setLayout(new BorderLayout(0, 7));
		createPopupMenu();
		setOpaque(false);

		JPanel findPanel = new JPanel();
		add(findPanel, BorderLayout.NORTH);
		findPanel.setLayout(new BorderLayout(0, 0));

		JPanel find = new JPanel();
		find.setBorder(new TitledBorder(null,
				"Th\u00F4ng tin t\u00ECm ki\u1EBFm", TitledBorder.LEADING,
				TitledBorder.TOP, null, SystemColor.textHighlight));
		findPanel.add(find, BorderLayout.NORTH);
		find.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.DEFAULT_COLSPEC, },
				new RowSpec[] { FormFactory.DEFAULT_ROWSPEC, }));

		// button search
		JLabel btnNewButton = new JLabel("Tìm kiếm");
		find.add(btnNewButton, "1, 1, right, default");

		searchField = new JXSearchField();
		searchField.setLayoutStyle(LayoutStyle.MAC);
		searchField.setPrompt("Nhập giá trị cần tìm");
		find.add(searchField, "3, 1, left, default");
		searchField.setColumns(27);

		// TODO advanced find
		JLabel label = new JLabel("");
		label.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				super.mousePressed(e);
				control.mousePressed(e);
			}
		});

		label.setToolTipText("Tìm kiếm nâng cao");
		label.setIcon(StoreImages.getIcon(StoreImages.ADVANCED_ICON));
		find.add(label, "5, 1, right, default");

		JButton button = new JButton("");
		button.setFocusable(false);
		button.setActionCommand("search");
		button.addActionListener(control);
		button.setIcon(StoreImages.getIcon(StoreImages.SEARCH_ICON));
		find.add(button, "7, 1");

		advanced = new JXCollapsiblePane();
		advanced.setCollapsed(true);
		advanced.setToolTipText("Dùng thi?t d?t các tìm ki?m nâng cao ho?c l?c thông tin");
		advanced.setBorder(new TitledBorder(UIManager
				.getBorder("TitledBorder.border"),
				"T\u00ECm ki\u1EBFm n\u00E2ng cao", TitledBorder.LEADING,
				TitledBorder.TOP, null, new Color(51, 153, 255)));
		findPanel.add(advanced, BorderLayout.CENTER);
		Container advanContainer = advanced.getContentPane();
		advanContainer.setLayout(new FormLayout(new ColumnSpec[] {
				FormFactory.DEFAULT_COLSPEC, FormFactory.RELATED_GAP_COLSPEC,
				FormFactory.GROWING_BUTTON_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_COLSPEC, FormFactory.DEFAULT_COLSPEC,
				FormFactory.RELATED_GAP_COLSPEC,
				ColumnSpec.decode("default:grow"), }, new RowSpec[] {
				FormFactory.DEFAULT_ROWSPEC, FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC, }));

		chck_name = new JCheckBox("Tên tài khoản");
		chck_name.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				txt_name.setEditable(chck_name.isSelected());
			}
		});

		advanContainer.add(chck_name, "1, 1");

		txt_name = new JTextField();
		txt_name.setEditable(false);
		advanContainer.add(txt_name, "3, 1, fill, default");
		txt_name.setColumns(10);

		check_author = new JCheckBox("Chủ tài khoản");
		check_author.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				txt_author.setEditable(check_author.isSelected());

			}
		});
		advanContainer.add(check_author, "5, 1");

		txt_author = new JTextField();
		txt_author.setEditable(false);
		advanContainer.add(txt_author, "7, 1, fill, default");
		txt_author.setColumns(10);

		check_lastloggin = new JCheckBox("Lần đăng nhập cuối");
		check_lastloggin.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				txt_lastloggin.setEditable(check_lastloggin.isSelected());
			}
		});
		advanContainer.add(check_lastloggin, "9, 1");

		txt_lastloggin = new JTextField();
		txt_lastloggin.setEditable(false);
		advanContainer.add(txt_lastloggin, "11, 1, fill, default");
		txt_lastloggin.setColumns(10);

		check_lock = new JCheckBox("Trạng thái");
		check_lock.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent arg0) {
				cbx_lock.setEnabled(check_lock.isSelected());
			}
		});
		advanContainer.add(check_lock, "1, 3");

		cbx_lock = new JComboBox<String>();
		cbx_lock.setEnabled(false);
		cbx_lock.setModel(new DefaultComboBoxModel<String>(new String[] {
				"Không bị khóa", "Bị khóa" }));
		advanContainer.add(cbx_lock, "3, 3, fill, default");
		cbx_lock.setEditable(false);

		check_exe = new JCheckBox("Quyền hạn");
		check_exe.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				cbx_exe.setEnabled(check_exe.isSelected());
			}
		});
		advanContainer.add(check_exe, "5, 3");

		cbx_exe = new JComboBox<String>();
		cbx_exe.setEnabled(false);
		cbx_exe.setModel(new DefaultComboBoxModel<String>(USER));
		advanContainer.add(cbx_exe, "7, 3, fill, default");
		cbx_exe.setEditable(false);

		textField_3 = new JTextField();
		advanContainer.add(textField_3, "11, 3, fill, default");
		textField_3.setColumns(10);

		JPanel centerList = new JPanel();
		centerList.setBorder(new TitledBorder(null,
				"Danh s\u00E1ch t\u00E0i kho\u1EA3n", TitledBorder.LEADING,
				TitledBorder.TOP, null, SystemColor.textHighlight));
		add(centerList, BorderLayout.CENTER);
		centerList.setLayout(new BorderLayout(0, 0));

		JScrollPane scrollPane = new JScrollPane();
		centerList.add(scrollPane, BorderLayout.CENTER);
		scrollPane
				.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
		scrollPane
				.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS);

		// TODO table
		table = new JXTable(tableModel);
		table.setHorizontalScrollEnabled(true);
		table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		scrollPane.setViewportView(table);

		table.setFillsViewportHeight(true);
		table.getTableHeader().setReorderingAllowed(false);
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseReleased(MouseEvent e) {
				super.mouseReleased(e);
				control.mouseReleased(e);
			}
		});

		table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {

					@Override
					public void valueChanged(ListSelectionEvent e) {
						if (e.getValueIsAdjusting() && account.isVisible()) {
							// FIXME
							if (table.getSelectedRow() != -1) {
								int realRow = table
										.convertRowIndexToModel(table
												.getSelectedRow());
								showInfor(realRow);
							}
						}
					}
				});

		DefaultCellEditor cellEditor = new DefaultCellEditor(new JCheckBox());
		final JCheckBox checkbox = (JCheckBox) cellEditor.getComponent();
		checkbox.setHorizontalAlignment(JCheckBox.CENTER);
		checkbox.setActionCommand(UICommand.CELL_CHECKBOX_CMD);
		checkbox.addActionListener(control);
		control.setCheckBoxEditor(checkbox);
		table.setDefaultEditor(Boolean.class, cellEditor);

		table.getColumnModel().getColumn(0)
				.setCellRenderer(new NumberRenderer());
		table.getColumnModel().getColumn(5)
				.setCellRenderer(new NumberRenderer());

		table.getColumnModel().getColumn(0).setPreferredWidth(81);
		table.getColumnModel().getColumn(0).setMaxWidth(81);
		table.getColumnModel().getColumn(1).setPreferredWidth(90);
		table.getColumnModel().getColumn(1).setMaxWidth(90);

		FormatFactory.formatHeader(table, SwingConstants.CENTER);
		FormatFactory.formatHighlighter(table, null);

		// TODO tool bar
		toolBar = new WebToolBar();
		FormatFactory.formatToolBar(toolBar);
		centerList.add(toolBar, BorderLayout.EAST);

		toolBar.add(FormatFactory.createButtonToolBar("Thêm",
				UICommand.SHOW_CMD, StoreImages.getIcon(StoreImages.NEW_ICON),
				control));
		toolBar.add(FormatFactory.createButtonToolBar("Sửa",
				UICommand.MODIFY_CMD,
				StoreImages.getIcon(StoreImages.EDIT_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Xóa",
				UICommand.DELETE_CMD,
				StoreImages.getIcon(StoreImages.DELETE_ICON), control));
		toolBar.add(FormatFactory.createButtonToolBar("Cập nhật",
				UICommand.REFRESH_CMD,
				StoreImages.getIcon(StoreImages.REFRESH_ICON), control));

		// TODO add panel
		account = new JPanel();
		account.setVisible(false);
		add(account, BorderLayout.SOUTH);
		account.setBorder(new TitledBorder(null,
				"Chi ti\u1EBFt t\u00E0i kho\u1EA3n", TitledBorder.LEADING,
				TitledBorder.TOP, null, SystemColor.textHighlight));
		account.setLayout(new FormLayout(
				new ColumnSpec[] { FormFactory.DEFAULT_COLSPEC,
						FormFactory.RELATED_GAP_COLSPEC,
						ColumnSpec.decode("default:grow"),
						FormFactory.RELATED_GAP_COLSPEC,
						FormFactory.DEFAULT_COLSPEC, }, new RowSpec[] {
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC,
						FormFactory.RELATED_GAP_ROWSPEC,
						FormFactory.DEFAULT_ROWSPEC, }));

		JLabel lblTnTiKhon = new JLabel();
		lblTnTiKhon.setText("<html>Tên tài khoản" + TestString.crossRed());
		account.add(lblTnTiKhon, "1, 1, left, default");

		a_username = new JXTextField();
		a_username.setName("user");
		a_username.addFocusListener(control);
		// a_username.setActionCommand("user");
		// a_username.addActionListener(control);
		a_username.addKeyListener(control);
		a_username.setPrompt("Tên dùng đăng nhập");
		account.add(a_username, "3, 1, fill, default");

		a_label1 = new JLabel("");
		a_label1.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		account.add(a_label1, "5, 1");

		JLabel lblChTiKhon = new JLabel();
		lblChTiKhon.setText("<html>Chủ tài khoản" + TestString.crossRed());
		account.add(lblChTiKhon, "1, 3, left, default");

		a_author = new JXTextField();
		a_author.setName("author");
		a_author.addFocusListener(control);
		// a_author.setActionCommand("author");
		// a_author.addActionListener(control);
		a_author.addKeyListener(control);
		a_author.setPrompt("Chủ sở hữu tài khoản");
		account.add(a_author, "3, 3, fill, default");

		a_label2 = new JLabel("");
		a_label2.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		account.add(a_label2, "5, 3");

		JLabel lblQuynHn = new JLabel();
		lblQuynHn.setText("Quyền hạn");
		account.add(lblQuynHn, "1, 5, left, default");

		a_combobox = new JComboBox<String>();
		a_combobox.setModel(new DefaultComboBoxModel<String>(USER));
		account.add(a_combobox, "3, 5, fill, default");

		a_label3 = new JLabel("");
		a_label3.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		account.add(a_label3, "5, 5");

		JLabel lblMtKhu = new JLabel();
		lblMtKhu.setText("<html>Mật khẩu" + TestString.crossRed());
		account.add(lblMtKhu, "1, 7, left, default");

		a_password = new JPasswordField();
		a_password
				.setToolTipText("Mật khẩu nên bao gồm chữ thường, chữ hoa, số và các kí tự đặc biệt");
		a_password.setName("pass");
		a_password.addFocusListener(control);
		// a_password.setActionCommand("pass");
		// a_password.addActionListener(control);
		a_password.addKeyListener(control);
		account.add(a_password, "3, 7, fill, default");

		a_label4 = new JLabel("");
		a_label4.setToolTipText(DEFAULT_PASS);
		a_label4.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		account.add(a_label4, "5, 7");

		JLabel lblNhpLiMt = new JLabel();
		lblNhpLiMt.setText("<html>Nhập lại MK" + TestString.crossRed());
		account.add(lblNhpLiMt, "1, 9, left, default");

		a_reenter = new JPasswordField();
		a_reenter.setToolTipText("Nhập lại mật khẩu để xác nhận độ chính xác");
		a_reenter.setName("repass");
		a_reenter.addFocusListener(control);
		// a_reenter.setActionCommand("repass");
		// a_reenter.addActionListener(control);
		a_reenter.addKeyListener(control);
		account.add(a_reenter, "3, 9, fill, default");

		a_label5 = new JLabel("");
		a_label5.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		account.add(a_label5, "5, 9");

		JPanel a_func = new JPanel();
		FlowLayout fl_a_func = (FlowLayout) a_func.getLayout();
		fl_a_func.setVgap(0);
		account.add(a_func, "1, 11, 5, 1, fill, fill");

		btnAdd = new JButton("Thêm");
		btnAdd.setActionCommand("add");
		btnAdd.addActionListener(control);
		a_func.add(btnAdd);

		JButton buttom_2 = new JButton("Thoát");
		buttom_2.setActionCommand("exit");
		buttom_2.addActionListener(control);
		a_func.add(buttom_2);

		// TODO list check box
		this.listChckBox.add(chck_name);
		this.listChckBox.add(check_lock);
		this.listChckBox.add(check_author);
		this.listChckBox.add(check_exe);
		this.listChckBox.add(check_lastloggin);
	}

	public static void setOpaque(JComponent comp, boolean b) {
		for (Component component : comp.getComponents()) {
			try {
				// if (comp.getComponentCount() == 1) {
				((JComponent) component).setOpaque(b);
				// System.out.println('h');
				// } else
				setOpaque((JComponent) component, b);
			} catch (Exception e) {
				// e.printStackTrace();
			}
		}
	}

	public void enableToolBar(boolean b) {
		table.setEnabled(b);
		Component[] list = toolBar.getComponents();
		for (Component component : list) {
			component.setEnabled(b);
		}
	}

	private void createPopupMenu() {
		popupMenu = new JPopupMenu();

		mntmThmTiKhon = new JMenuItem("Thêm");
		mntmThmTiKhon.setActionCommand(UICommand.SHOW_CMD);
		mntmThmTiKhon.addActionListener(control);
		popupMenu.add(mntmThmTiKhon);

		popupMenu.addSeparator();

		mnNotify = new JMenuItem("Sửa");
		mnNotify.setActionCommand(UICommand.MODIFY_CMD);
		mnNotify.addActionListener(control);
		popupMenu.add(mnNotify);

		mnDel = new JMenuItem("Xóa");
		mnDel.setActionCommand(UICommand.DELETE_CMD);
		mnDel.addActionListener(control);
		popupMenu.add(mnDel);
	}

	public void setEditable(String name) {
		switch (name) {
		case "name":
			txt_name.setEditable(chck_name.isSelected());
			break;
		case "author":
			txt_author.setEditable(check_author.isSelected());
			break;
		case "lastloggin":
			txt_lastloggin.setEditable(check_lastloggin.isSelected());
			break;
		case "exe":
			cbx_exe.setEnabled(check_exe.isSelected());
			break;
		case "lock":
			cbx_lock.setEnabled(check_lock.isSelected());
			break;
		}
	}

	// used by cancel button
	public void exit() {
		clearAddPanel();
		// clearModifyPanel();
		account.setVisible(false);
		enableToolBar(true);
	}

	public void clearAddPanel() {
		// set text
		a_username.setText("");
		a_author.setText("");
		a_combobox.setSelectedIndex(0);
		a_password.setText("");
		a_reenter.setText("");
		// set default icon, tool tip text
		a_label1.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		a_label1.setToolTipText(DEFAULT_USERNAME);
		a_label2.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		a_label2.setToolTipText(DEFAULT_AUTHOR);
		a_label3.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		a_label4.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		a_label5.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
		a_label5.setToolTipText(DEFAULT_PASS);
	}

	public void showInfor(int row) {
		Account acc = (Account) tableModel.getDataRow(row);
		a_username.setText(acc.getName());
		a_author.setText(acc.getAuthor());
		a_combobox.setSelectedItem(acc.getPower());
	}

	public void showAddPanel() {
		modify = false;
		clearSelectionTable();
		showPanel();
	}

	public void showModifyPanel() {
		modify = true;
		showInfor(getSelectedRealRow());
		showPanel();
	}

	private void showPanel() {
		enableToolBar(false);
		btnAdd.setText(modify ? "Lưu" : "Thêm");
		btnAdd.setActionCommand(modify ? UICommand.SAVE_CMD : UICommand.ADD_CMD);
		account.setVisible(true);
	}

	public void showAdvancedFind() {
		advanced.setCollapsed(!advanced.isCollapsed());
	}

	public void enableMenu(boolean b) {
		mntmThmTiKhon.setEnabled(b);
		mnDel.setEnabled(b);
		mnNotify.setEnabled(b);
	}

	public void showPopupMenu(MouseEvent e) {
		if (e.isPopupTrigger()) {
			enableMenu(table.isEnabled());
			popupMenu.show(e.getComponent(), e.getX(), e.getY());
		}
	}

	// check user name too long
	public boolean checkUserName(int key) {
		String tmp = a_username.getText().trim();
		Account account = tableModel.getAccountAtRow(getSelectedRealRow());
		if (tmp.length() == 0) {
			changeIcon(a_label1, -1);
			a_label1.setToolTipText(DEFAULT_USERNAME);
		} else if (tmp.length() < 5 || tmp.length() > 45) {
			changeIcon(a_label1, 0);
			a_label1.setToolTipText(DEFAULT_USERNAME);
		} else {
			for (int i = 0; i < tableModel.getRowCount(); i++) {
				Account acc = tableModel.getAccountAtRow(i);
				if (tmp.equalsIgnoreCase(acc.getName())) {
					if (account != null
							&& tmp.equalsIgnoreCase(account.getName())) {
						continue;
					}
					changeIcon(a_label1, 0);
					a_label1.setToolTipText("Tên tài khoản đã được sử dụng");
					return false;
				}
			}
			changeIcon(a_label1, 1);
			a_label1.setToolTipText(DEFAULT_USERNAME);
			if (key == KeyEvent.VK_ENTER)
				a_author.requestFocus();
			return true;
		}
		return false;
	}

	// check author
	public void checkAuthor(int key) {
		String tmp = a_author.getText().trim();
		if (tmp.equals("")) {
			changeIcon(a_label2, -1);
			a_label2.setToolTipText(DEFAULT_AUTHOR);
			return;
		}
		for (int i = 0; i < tableModel.getRowCount(); i++) {
			Account acc = (Account) tableModel.getDataRow(i);
			if (tmp.equalsIgnoreCase(acc.getAuthor())) {
				changeIcon(a_label2, 2);
				a_label2.setToolTipText("Chủ tài khoản này đã có tài khoản khác trên hệ thống");
				return;
			}
		}
		changeIcon(a_label2, 1);
		a_label2.setToolTipText(DEFAULT_AUTHOR);
		if (key == KeyEvent.VK_ENTER)
			a_password.requestFocus();
	}

	public boolean checkPass(int key) {
		char[] tmp = a_password.getPassword();
		if (tmp.length == 0) {
			changeIcon(a_label4, -1);
		} else if (tmp.length < 6) {
			changeIcon(a_label4, 0);
		} else {
			changeIcon(a_label4, 1);
			if (key == KeyEvent.VK_ENTER)
				a_reenter.requestFocus();
			checkReenter();
			return true;
		}
		return false;
	}

	public boolean checkReenter() {
		char[] tmp = a_reenter.getPassword();
		if (tmp.length == 0) {
			changeIcon(a_label5, -1);
			a_label5.setToolTipText(DEFAULT_PASS);
		} else if (Arrays.equals(tmp, a_password.getPassword())) {
			changeIcon(a_label5, 1);
			return true;
		} else {
			changeIcon(a_label5, 0);
			a_label5.setToolTipText("Mật khẩu không trùng khớp");
		}
		return false;
	}

	// use update accoun
	public boolean isEmptyPassField() {
		return a_password.getPassword().length == 0
				&& a_reenter.getPassword().length == 0;
	}

	public void changeIcon(JLabel label, int type) {
		String icon = null;
		switch (type) {
		case 0: // invalid
			icon = StoreImages.DELETE_ICON;
			break;
		case 1: // valid
			icon = StoreImages.VALID_ICON;
			break;
		case 2: // waring
			icon = StoreImages.WARNING_ICON;
			break;
		default:
			label.setIcon(StoreImages.getIcon(StoreImages.ABOUT_ICON));
			return;
		}
		label.setIcon(StoreImages.getIcon(icon));
	}

	public String[] getQueryAdd() {
		String[] query = new String[4];
		query[0] = a_username.getText();
		query[1] = a_author.getText();
		query[2] = a_combobox.getItemAt(a_combobox.getSelectedIndex());
		query[3] = new String(a_password.getPassword());
		return query;
	}

	public Account getAccountUpdate(Account account, boolean newPass) {
		Account tmp = getAccountEdit();
		tmp.setId(account.getId());
		if (newPass)
			tmp.setPass(Encryption.encrypt(account.getId()
					+ new String(a_password.getPassword())));
		else
			tmp.setPass(account.getPass());
		return tmp;
	}

	public int getSelectedRealRow() {
		try {
			return table.convertRowIndexToModel(table.getSelectedRow());
		} catch (IndexOutOfBoundsException e) {
			return -1;
		}
	}

	public String getUserNameSelected() {
		Account acc = tableModel.getAccountAtRow(getSelectedRealRow());
		if (acc != null)
			return acc.getName();
		return "";
	}

	public boolean checkUserName(String... userName) {
		Account acc = tableModel.getAccountAtRow(getSelectedRealRow());
		if (acc != null)
			for (int i = 0; i < userName.length; i++) {
				if (acc.getName().equalsIgnoreCase(userName[i]))
					return true;
			}
		return false;
	}

	public JButton getBtnAdd() {
		return btnAdd;
	}

	public int getSetlectedRow() {
		return table.getSelectedRow();
	}

	public String getSearchText() {
		return searchField.getText();
	}

	public void setTextName() {
		this.txt_name.setText(this.searchField.getText());
	}

	public boolean isSelectedTable() {
		for (int i = 0; i < listChckBox.size(); i++) {
			if (listChckBox.get(i).isSelected())
				return true;
		}
		return false;
	}

	public String createSQL() {
		String sql = "";
		for (int i = 0; i < listChckBox.size(); i++) {
			if (listChckBox.get(i).isSelected()) {
				sql = getSql(i, sql);
			}
		}
		return sql;
	}

	public String getSql(int id, String sql) {
		if (!sql.equals(""))
			sql += "AND ";
		switch (id) {
		case 1:
			sql += "account.lock = " + cbx_lock.getSelectedIndex() + " ";
			break;
		case 2:
			sql += "author LIKE '%" + txt_author.getText() + "%' ";
			break;
		case 3:
			sql += "exe = '" + cbx_exe.getSelectedItem() + "' ";
			break;
		case 4:
			sql += "last_loggin = '" + txt_lastloggin.getText() + "' ";
			break;
		default:
			sql += "name LIKE '%" + txt_name.getText() + "%' ";
			break;
		}
		return sql;
	}

	public static void main(String[] args) {
		WebLookAndFeel.install();
		JFrame frame = new JFrame();
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		SystemTableModel tableModel = new SystemTableModel();
		SystemController control = new SystemController(tableModel);
		frame.getContentPane().add(control.getView());
		frame.pack();
		frame.setVisible(true);
	}

	public void clearSelectionTable() {
		this.table.clearSelection();
	}

	public Account getAccountEdit() {
		return new Account(a_username.getText(), a_author.getText(),
				a_combobox.getItemAt(a_combobox.getSelectedIndex()));
	}

	public Account getAccountSelected() {
		return tableModel.getAccountAtRow(getSelectedRealRow());
	}

}